﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Microsoft.Http;
using WikeSoft.Core;


namespace WikeSoft.Global
{
    public class FileProcess
    {



        private static async Task<string> UploadFileAsync(FileEntity fl)
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            formatter.Serialize(ms, fl);
            ms.Position = 0;

            System.Net.Http.HttpContent content = new StreamContent(ms);
            string url = System.Configuration.ConfigurationManager.AppSettings["FileUploadUrl"];

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            Task<System.Net.Http.HttpResponseMessage> response = client.PostAsync(string.Format("{0}/file/upload", url), content);
            response.Result.EnsureSuccessStatusCode();

            string responseBody = await response.Result.Content.ReadAsStringAsync();
            string[] str = (string[])XmlSerializeUtil.Deserialize(typeof(string[]), responseBody);
            return responseBody;
        }

        public static string[] UploadFile(FileEntity fl)
        {

            IFormatter formatter = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            formatter.Serialize(ms, fl);
            ms.Position = 0;

            var content = Microsoft.Http.HttpContent.Create(ms, "application/octet-stream", ms.Length);
            string url = System.Configuration.ConfigurationManager.AppSettings["FileUploadUrl"];
            if (string.IsNullOrEmpty(url))
            {
                throw new ApplicationException("AppSettings Must config FileUploadUrl");
            }
            var client = new Microsoft.Http.HttpClient();


            using (var response = client.Post(string.Format("{0}/file/upload", url), content))
            {

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    response.Content.LoadIntoBuffer();

                    string[] strs = response.Content.ReadAsDataContract<string[]>(typeof(string[]));

                    for (int i = 0; i < strs.Length; i++)
                    {
                        strs[i] = string.Format("{0}/{1}", url, strs[i]);
                    }


                    return strs;

                }
                else
                {
                    Encoding encode = System.Text.Encoding.GetEncoding("GBK");
                    string errorMsg = response.Content.ReadAsString();
                    Regex rg = new Regex(@"<P><B>Details[:：][\s]*<\/B>([^\/]+)</P>");
                    if (rg.Match(errorMsg).Success)
                    {
                        errorMsg = rg.Match(errorMsg).Result("$1");
                    }

                    throw new ApplicationException(errorMsg);
                }
            }
        }

        public static OperateResult DeleteFile(List<string> paths)
        {
            string root = System.Configuration.ConfigurationManager.AppSettings["FileUploadUrl"];
            if (string.IsNullOrEmpty(root))
            {
                throw new ApplicationException("AppSettings Must config FileUploadUrl");
            }
            paths = paths.Select(x => { return x.Replace(root, ""); }).ToList();
            IFormatter formatter = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            formatter.Serialize(ms, paths);
            ms.Position = 0;

            var content = Microsoft.Http.HttpContent.Create(ms, "application/octet-stream", ms.Length);
            string url = System.Configuration.ConfigurationManager.AppSettings["FileUploadUrl"];
            if (string.IsNullOrEmpty(url))
            {
                throw new ApplicationException("AppSettings Must config FileUploadUrl");
            }
            var client = new Microsoft.Http.HttpClient();


            using (var response = client.Post(string.Format("{0}/file/delete", url), content))
            {

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    response.Content.LoadIntoBuffer();

                    var strs = response.Content.ReadAsDataContract<string>(typeof(string));
                    using (StringReader sr = new StringReader(strs))
                    {
                        XmlSerializer xmldes = new XmlSerializer(typeof(OperateResult));
                        return xmldes.Deserialize(sr) as OperateResult;
                    }
                }
                else
                {
                    Encoding encode = System.Text.Encoding.GetEncoding("GBK");
                    string errorMsg = response.Content.ReadAsString();
                    Regex rg = new Regex(@"<P><B>Details[:：][\s]*<\/B>([^\/]+)</P>");
                    if (rg.Match(errorMsg).Success)
                    {
                        errorMsg = rg.Match(errorMsg).Result("$1");
                    }

                    throw new ApplicationException(errorMsg);
                }
            }
        }

    }
}
